package com.jintoufs.weixin.divided;

import com.google.common.collect.Maps;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.interceptor.ParamCheck;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.divided.DividedService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.util.valid.ValidUtil;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.view.json.AbstractJackson2View;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by yangpeng on 2018/2/28.
 */
@RestController
@RequestMapping("/api/divided")
public class DividedAction {
    @Resource
    private DividedService dividedService;

    @Resource
    private CustomerService customerService;



    @GetMapping("/detail")
    @ResponseBody
    public AjaxMsg getDivided(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try{
            Customer customer = customerService.getByToken(token);
            if (ValidUtil.isEmpty(customer)) {
                throw new RuntimeException("用户验证失败");
            }
            List<Map> divideds = dividedService.getDivided(customer.getId());
            ajaxMsg.setDatas(divideds);
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    /**
     * 分销订单列表 新版
     *
     * @param token
     * @param status
     * @return
     */
    @ParamCheck(params = "token")
    @GetMapping("/shareOrders")
    @ResponseBody
    public AjaxMsg getShareOrderList(String token, String status) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Customer customer = customerService.getByToken(token);
            if (ValidUtil.isEmpty(customer)) {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setDatas("authfaild");
                return ajaxMsg;
            }
            Map param = new HashMap(3);
            param.put("status", status.split(","));
            param.put("customerId", customer.getId());
            if("0".equals(customer.getType())){
                param.put("isGys", "gys");
            }
            List shareOrders = dividedService.getShareOrders(param);
            ajaxMsg.setDatas(shareOrders);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
        }
        return ajaxMsg;
    }

    /**
     *
     * @param token
     * @param ids
     * @return 批量读分销订单
     */
    @GetMapping("/readOrder")
    @ParamCheck(params = "token,ids")
    @ResponseBody
    public AjaxMsg readOrder(String token,String ids){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            dividedService.readOrder(token, ids, ajaxMsg);
        } catch (Exception e) {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    /**
     * 查询是否有未读分销订单
     * @param token
     * @return
     */
    @ParamCheck(params = "token")
    @GetMapping("/hasNew")
    @ResponseBody
    public AjaxMsg hasNew(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        Customer customer = customerService.getByToken(token);
        if (ValidUtil.isEmpty(customer)) {
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("认证失败");
            ajaxMsg.setDatas("authfaild");
        }
        Map param = new HashMap(3);
        //未读的
        param.put("readStatus","0");
        //新订单
        param.put("status", "1".split(","));
        param.put("customerId", customer.getId());
        List cur0 = dividedService.getShareOrders(param);
        param.put("status", "5".split(","));
        List cur1 = dividedService.getShareOrders(param);
        //6-已完成（已完成)
        param.put("status", "6".split(","));
        List cur2 = dividedService.getShareOrders(param);
        //2,3,4-已失效（取消，退款中，已退款)
        param.put("status", "2,3,4".split(","));
        List cur3 = dividedService.getShareOrders(param);
        Map result = new HashMap();
        result.put("cur0", cur0.size() > 0);
        result.put("cur1", cur1.size() > 0);
        result.put("cur2", cur2.size() > 0);
        result.put("cur3", cur3.size() > 0);
        ajaxMsg.setDatas(result);
        return ajaxMsg;
    }

    @ParamCheck(params = "token")
    @ResponseBody
    @GetMapping("/getMyFunds")
    public AjaxMsg getMyFunds(String token){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try{
            Customer customer = customerService.getByToken(token);
            BigDecimal totalShare = new BigDecimal("0");
            if (!ValidUtil.isEmpty(customer)){
                List<Map> shares = dividedService.getSharesByUser(customer.getId());
                if(!ValidUtil.isEmpty(shares)){
                    for (Map m : shares) {
                        String recommendId = (String)m.get("recommendId");
                        String spreadId = (String) m.get("spreadId");
                        BigDecimal price =(BigDecimal) m.get("price");
                        BigDecimal actPrice = (BigDecimal)m.get("actPrice");
                        BigDecimal sharePrice = (BigDecimal)m.get("sharePrice");
                        if (customer.getId().equals(recommendId)) {
                            //推荐人分润 没有推广人
                            if (ValidUtil.isEmpty(spreadId)) {
                                totalShare = totalShare.add(actPrice.subtract(sharePrice));
                            }else{
                                //有推广人
                                BigDecimal temp =  actPrice.subtract(sharePrice).multiply(new BigDecimal(customer.getDividedNumber()));
                                totalShare = totalShare.add(temp);
                            }
                        } else if (customer.getId().equals(spreadId)) {
                            //推广人分润
                            totalShare = totalShare.add(
                                    actPrice.subtract(sharePrice).multiply(new BigDecimal("0.5"))
                            );
                        }else{
                            throw new RuntimeException("系统繁忙,请稍后再试");
                        }
                    }
                }
                ajaxMsg.setDatas(totalShare.floatValue());
            }else {
                ajaxMsg.setCode(AjaxMsg.FAILURE);
                ajaxMsg.setDatas("authfail");
                ajaxMsg.setMessage("用户验证失败");
            }
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage(e.getMessage());
            return ajaxMsg;
        }
        return ajaxMsg;
    }
}
